package com.dongjiantong.app.controller.farmrecords.cowRecords;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.dto.CowRecordDto;
import com.dongjiantong.farmrecords.model.FarmRecordsCowRecords;
import com.dongjiantong.farmrecords.model.FarmRecordsDiagnosis;
import com.dongjiantong.farmrecords.model.FarmRecordsImmunization;
import com.dongjiantong.farmrecords.service.FarmRecordsCowRecordsService;
import com.dongjiantong.farmrecords.service.FarmRecordsDiagnosisService;
import com.dongjiantong.farmrecords.service.FarmRecordsImmunizationService;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 牛档案
 * @author Lee
 * @date 2018/1/12
 */
@Slf4j
@OpenBean
public class FarmRecordsBullController {
    @Reference(version = "1.0.0",retries = 0,timeout = 6000)
    private FarmRecordsCowRecordsService farmRecordsBullRecordsService;
    @Reference(version = "1.0.0",retries = 0,timeout = 6000)
    private FarmRecordsImmunizationService farmRecordsImmunizationService;
    @Reference(version = "1.0.0",retries = 0,timeout = 6000)
    private FarmRecordsDiagnosisService farmRecordsDiagnosisService;

    /**
     * 新增牛档案
     * @param cowRecord
     * @param toStatus
     * @return
     */
    @OpenMethod(key = "app.farmrecords.bull.createOne",
                            paramNames = {"cowRecord","toStatus"},
                            httpMethods = RequestMethod.POST)
    public Response<Map<String,Object>> createOne(@RequestParam(required = false) FarmRecordsCowRecords cowRecord,
                                                  @RequestParam(required = false)Integer toStatus) {
        Map<String,Object> result = null;
        LoginInfo loginInfo = UserUtil.getCurrentUser();

        result = farmRecordsBullRecordsService.createOne(loginInfo,cowRecord,toStatus);

        if (result == null) {
            result = Maps.newHashMap();
            result.put("receiptId",null);
        }

        return Response.ok(result);
    }

    /**
     * 政府端分页查看牛档案
     * @param farmId
     * @param fromDate
     * @param toDate
     * @param pageNum
     * @param pageSize
     * @param cowNumber
     * @return
     */
    @OpenMethod(key = "app.farmrecords.bull.selectByFarmIdAndDate",
            paramNames = {"farmId","fromDate","status","toDate","pageNum","pageSize","cowNumber"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsCowRecords>> selectByFarmIdAndDate(
            @RequestParam(required = false) Long farmId,
            @RequestParam(required = false) String fromDate,
            @RequestParam(required = false) List<Integer> status,
            @RequestParam(required = false) String toDate,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String cowNumber){
        if (farmRecordsBullRecordsService == null){ throw new OPServerException("请检查 farmRecordsBullRecordsService 服务"); }

        Map map = Maps.newHashMap();
        Long userId = UserUtil.getUserId();
        map.put("userId",userId);

        if (pageNum == null) { pageNum = 1; }
        if (pageSize == null) { pageSize = 20; }

        if (farmId != null){
            //如果养殖场id不为空,则根据养殖场id查询
            map.put("farm_id",farmId);
        }

        if (status.size() > 0) {
            map.put("statusList",status);
        }

        if (!Strings.isNullOrEmpty(cowNumber)) { map.put("cow_number",cowNumber); }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!Strings.isNullOrEmpty(fromDate)){
                Date startDate = sdf.parse(fromDate);
                map.put("startDate",startDate);
            }
            if (!Strings.isNullOrEmpty(toDate)){
                Date endDate = sdf.parse(toDate);
                map.put("endDate",endDate);
            }

            PageInfo<FarmRecordsCowRecords> farmRecordsBullRecordsPageInfo = farmRecordsBullRecordsService.selectByMap(pageNum,pageSize,map);

            return Response.ok(farmRecordsBullRecordsPageInfo);

        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR, HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 养殖端
     * 根据提交状态分页查询列表
     * @param farmId
     * @param status
     * @return
     */
    @OpenMethod(key = "app.farmrecords.bull.selectListByStatus",
            paramNames = {"farmId","status","pageSize","pageNum","cowNumber"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<CowRecordDto>> selectListByStatus(@RequestParam(required = false) Long farmId,
                                                                       @RequestParam(required = false) List<Integer> status,
                                                                       @RequestParam(required = false) Integer pageSize,
                                                                       @RequestParam(required = false) Integer pageNum,
                                                                         @RequestParam(required = false) String cowNumber){
        if (farmRecordsBullRecordsService == null){ throw new OPServerException("farmRecordsBullRecordsService 服务为空,请重启服务后重试"); }
        if (farmId == null){ throw new OPServerException("养殖场id不能为空,请检查后重试"); }

        if (pageSize == null){ pageSize = 20; }
        if (pageNum == null){ pageNum = 1; }

        try {
            PageInfo<CowRecordDto> cowRecordDtoPageInfo = farmRecordsBullRecordsService.selectListByStatus(pageNum,pageSize,status,farmId,cowNumber);
            return Response.ok(cowRecordDtoPageInfo);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 根据主键id查询对应牛档案
     * @param id
     * @return
     */
    @OpenMethod(key = "app.farmrecords.bull.selectById",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<FarmRecordsCowRecords> selectById(@RequestParam(required = false)Long id){
        if (id == null) { throw new OPServerException(HttpCode.BAD_REQUEST,"请求的id不能为空"); }

        try {
            if (farmRecordsBullRecordsService == null){ throw new OPServerException("farmRecordsBullRecordsService 为null,请检查"); }

            FarmRecordsCowRecords farmRecordsBullRecords = farmRecordsBullRecordsService.selectByPrimaryKey(id);

            return Response.ok(farmRecordsBullRecords);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 更新牛档案
     * @param cowRecord 请求的对象
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @OpenMethod(key = "app.farmrecords.bull.updateByIdOrNumber",
            paramNames = {"cowRecord","toStatus"},
            httpMethods = RequestMethod.POST)
    public Response<Object> updateByIdOrNumber(@RequestBody(required = false) FarmRecordsCowRecords cowRecord,
                                               @RequestParam(required = false) Integer toStatus){
        if (cowRecord == null){
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求参数对象不能为空");
        }else{
            if (farmRecordsBullRecordsService == null){ throw new OPServerException("farmRecordsBullRecordsService 为null,请检查"); }

            if (cowRecord.getId() == null){
                throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST,HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
            }else {
                Integer con = farmRecordsBullRecordsService.updateByIdOrNumber(cowRecord,toStatus);

                Map<String,Object> map = Maps.newHashMap();
                if (con == 1) {
                    map.put("updateResult","true");
                }else {
                    map.put("updateResult","false");
                }

                return Response.ok(map);
            }
        }
    }

    /*
     * 更新免疫单据耳标号
     * 更新免疫记录(只更新免疫记录主表 耳标)
     */
    @OpenMethod(key = "app.farmrecords.bull.updateEarNumber",
            paramNames = {"cowRecord"},
            httpMethods = RequestMethod.POST)
    public Response<Map<String,Object>> updateEarNumber(FarmRecordsCowRecords cowRecord){
        Map<String,Object> map = Maps.newHashMap();
        boolean result = false;
        LoginInfo loginInfo = UserUtil.getCurrentUser();

        //原有耳标
        String beforeEarTogNumber = null;

        //更新单据耳标
        farmRecordsBullRecordsService.updateByPrimaryKeySelective(cowRecord);

        FarmRecordsCowRecords farmRecordsCowRecords = farmRecordsBullRecordsService.selectByPrimaryKey(cowRecord.getId());
        if (farmRecordsCowRecords != null) {
            if (!Strings.isNullOrEmpty(farmRecordsCowRecords.getEar_tag_number())) {
                beforeEarTogNumber = farmRecordsCowRecords.getEar_tag_number();
            }
        }

        String earTagNumber = cowRecord.getEar_tag_number();

        if (!Strings.isNullOrEmpty(earTagNumber)) {
            //更新免疫耳标
            farmRecordsImmunizationService.updateEarNumberByCowRelateId(cowRecord.getId(),cowRecord.getEar_tag_number());
            //更新诊疗耳标
            farmRecordsDiagnosisService.updateEarNumberByCowRelateId(cowRecord.getId(),cowRecord.getEar_tag_number());
            result = farmRecordsBullRecordsService.updateEarNumber(earTagNumber,beforeEarTogNumber);
        }

        map.put("result",result);

        return Response.ok(map);
    }
}
